package org.linlinjava.litemall.wx.service;

import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.systemConfig.GetRegionService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.service.LitemallWalletRecordService;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.wx.util.CreateSn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 团购
 *
 * @author zhy
 * @date 2019-07-12 9:22
 **/
@Service
public class GroupBuyService extends GetRegionService {
	@Resource
	private LitemallGroupBuyMapper litemallGroupBuyMapper;

	@Resource
	private LitemallGroupBuyDetailMapper litemallGroupBuyDetailMapper;

	@Resource
	private LitemallGoodsMapper litemallGoodsMapper;

	@Resource
	private PlatformTransactionManager txManager;

	@Resource
	private LitemallGroupBuyUserMapper groupBuyUserMapper;

	@Resource
	private LitemallOrderMapper litemallOrderMapper;

	@Resource
	private LitemallUserMapper userMapper;

	@Resource
	private CreateSn createSn;

	private NotifyService notifyService;

	private LitemallOrderService orderService;

	private LitemallOrderGoodsService orderGoodsService;

	private LitemallWalletRecordService walletRecordService;

	private LitemallUserService userService;

	public GroupBuyService(
		LitemallOrderService orderService,NotifyService notifyService, LitemallOrderGoodsService orderGoodsService, LitemallWalletRecordService walletRecordService, LitemallUserService userService) {
		this.orderService = orderService;
		this.orderGoodsService = orderGoodsService;
		this.walletRecordService = walletRecordService;
		this.userService = userService;
		this.notifyService = notifyService;
	}

	public LitemallGroupBuy getGroupById(Integer id) {
		return litemallGroupBuyMapper.selectByPrimaryKey(id);
	}

	public LitemallGroupBuyDetail getDetail(Integer groupId, Integer id) {
		LitemallGroupBuyDetailExample example = new LitemallGroupBuyDetailExample();
		example.or().andGroupIdEqualTo(groupId).andGoodIdEqualTo(id);
		LitemallGroupBuyDetail.Column[] column =
			new LitemallGroupBuyDetail.Column[] {LitemallGroupBuyDetail.Column.id, LitemallGroupBuyDetail.Column.leastNum, LitemallGroupBuyDetail.Column.orderLeftNum};
		return litemallGroupBuyDetailMapper.selectOneByExampleSelective(example, column);
	}

	public List<LitemallGroupBuyDetail> getGroupByList(Integer groupId) {
		LitemallGroupBuyDetailExample example = new LitemallGroupBuyDetailExample();
		example.or().andGroupIdEqualTo(groupId).andDeletedEqualTo(false);
		return litemallGroupBuyDetailMapper.selectByExample(example);
	}

	public List<LitemallGroupBuyDetail> getGoodList(Integer groupId) {
		LitemallGroupBuyDetailExample example = new LitemallGroupBuyDetailExample();
		example.or().andGroupIdEqualTo(groupId).andDeletedEqualTo(false);
		return litemallGroupBuyDetailMapper.selectByExample(example);
	}

	public int updateStatus(List<Integer> orderIds) {
		return litemallOrderMapper.updateStatus(orderIds);
	}

	public int updateUserStatus(List<Integer> orderIds, short status) {
		return groupBuyUserMapper.updateStatus(orderIds, status);
	}

	public List<LitemallGroupBuyUser> getUsers(Integer groupDetailId) {
		LitemallGroupBuyUserExample example = new LitemallGroupBuyUserExample();
		example.or().andGroupDetailIdEqualTo(groupDetailId);
		return groupBuyUserMapper.selectByExample(example);
	}

	public void sendGroupSuccessMsg(Integer userId, String goodName, short orderNum) {
		LitemallUser litemallUser = userService.findById(userId);
		String[] params = new String[] {goodName, orderNum + "个", "拼团成功，等待发货。"};
		notifyService.notifyWxTemplate(litemallUser.getWeixinOpenid(), NotifyType.GROUPSUCCESS, params);
	}

	@Transactional
	public void updateUserCount(Integer integeal, BigDecimal price, Integer userId, Integer groupUserId, String goodName) {
		// 用户账户
		LitemallUser litemallUser = userService.findById(userId);
		litemallUser.setIntegral(litemallUser.getIntegral() + integeal);
		litemallUser.setBalance(litemallUser.getBalance().add(price));
		userMapper.updateByPrimaryKey(litemallUser);

		//钱包记录
		LitemallWalletRecord walletRecord = new LitemallWalletRecord();
		String orderSn = createSn.createSn();
		walletRecord.setUserId(litemallUser.getId());
		walletRecord.setType(new Byte("4"));
		walletRecord.setModifyAmount(price);
		walletRecord.setModifyIntegral(integeal);
		walletRecord.setPayId(orderSn);
		walletRecord.setPayTime(LocalDateTime.now());
		walletRecord.setModifyTime(LocalDateTime.now());
		walletRecord.setModifyReason("拼团退款");
		walletRecord.setRecordSn(orderSn);
		walletRecordService.add(walletRecord);

		//groupBuyUser订单状态
		LitemallGroupBuyUser litemallGroupBuyUser = new LitemallGroupBuyUser();
		litemallGroupBuyUser.setId(groupUserId);
		litemallGroupBuyUser.setOrderStatus((short)3);
		groupBuyUserMapper.updateByPrimaryKeySelective(litemallGroupBuyUser);

		//发送模板消息，提示拼团退款成功
		String[] params = new String[] {goodName, integeal + "积分/" + price + "爱币", "拼团人数不足,订单金额已退至您原账户"};
		notifyService.notifyWxTemplate(litemallUser.getWeixinOpenid(), NotifyType.GROUPFAIL, params);
	}

	public LitemallGroupBuy findPassed() {
		LitemallGroupBuyExample example = new LitemallGroupBuyExample();
		example.or().andEndTimeLessThan(LocalDateTime.now()).andRunningFlagEqualTo((short)2);
		return litemallGroupBuyMapper.selectOneByExample(example);
	}

	public int updateRunningFlag(LitemallGroupBuy litemallGroupBuy) {
		return litemallGroupBuyMapper.updateByPrimaryKeySelective(litemallGroupBuy);
	}

	public LitemallGroupBuy findCurrent() {
		LitemallGroupBuyExample example = new LitemallGroupBuyExample();
		example.or().andStartTimeLessThanOrEqualTo(LocalDateTime.now()).andEndTimeGreaterThanOrEqualTo(LocalDateTime.now());
		return litemallGroupBuyMapper.selectOneByExample(example);
	}

	public LitemallGroupBuy findNext() {
		LitemallGroupBuyExample example = new LitemallGroupBuyExample();
		example.or().andStartTimeGreaterThan(LocalDateTime.now()).andRunningFlagEqualTo((short)1);
		example.orderBy(LitemallGroupBuy.Column.startTime.asc());
		List<LitemallGroupBuy> litemallGroupBuys = litemallGroupBuyMapper.selectByExample(example);
		if (litemallGroupBuys.size() > 0) {
			return litemallGroupBuys.get(0);
		} else {
			return null;
		}
	}

	public List<LitemallGroupDetailsVo> getGood(List<Integer> ids, Integer groupId) {
		return litemallGoodsMapper.getGroupBuyGood(ids, groupId);
	}

	public Object submitOrder(
		LitemallUser litemallUser, Integer goodsIntegeal, BigDecimal goodsPrice, LitemallProduct litemallProduct, Short num, Integer groupId, LitemallAddress address, LitemallGoods litemallGoods) {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);
		LitemallOrder order = new LitemallOrder();
		try {
			// 扣减拼团商品库存
			int nums = litemallGroupBuyDetailMapper.reduceNum(groupId, Integer.valueOf(num));
			if (nums == 0) {
				txManager.rollback(status);
				return ResponseUtil.fail(403, "拼团人数已满");
			}
			//创建订单

			order.setUserId(litemallUser.getId());
			order.setOrderSn(orderService.generateOrderSn(litemallUser.getId()));
			order.setAddTime(LocalDateTime.now());
			order.setOrderStatus(OrderUtil.STATUS_CREATE);
			order.setConsignee(address.getName());
			order.setMobile(address.getMobile());
			order.setAddress(getdetailedAddress(address));
			order.setGoodsPrice(goodsPrice);
			order.setGoodsIntegral(goodsIntegeal);
			order.setGiveIntegral(0);
			order.setGivePrice(new BigDecimal(0));
			order.setFreightPrice(new BigDecimal(0));
			order.setCouponPrice(new BigDecimal(0));
			order.setGiveBalance(new BigDecimal(0));
			order.setActualIntegral(goodsIntegeal);
			order.setDeleted(true);
			//TODO 修改订单信息 价格等
			order.setOrderPrice(goodsPrice);
			order.setActualPrice(goodsPrice);
			order.setMechanismType(false);
			//TODO 添加订单表项
			orderService.add(order);

			//创建订单详情
			LitemallOrderGoods orderGoods = new LitemallOrderGoods();
			orderGoods.setOrderId(order.getId());
			orderGoods.setGoodsId(litemallProduct.getGoodsId());
			orderGoods.setGoodsSn(litemallGoods.getGoodsSn());
			orderGoods.setProductId(litemallProduct.getId());
			orderGoods.setGoodsName(litemallGoods.getName());
			orderGoods.setPicUrl(litemallGoods.getPicUrl());
			orderGoods.setPrice(litemallProduct.getPrice());
			orderGoods.setNumber(num);
			orderGoods.setIntegral(litemallProduct.getIntegral());
			orderGoods.setPriceFlag((byte)1);
			orderGoods.setIntegralFlag((byte)1);
			orderGoods.setSpecifications(litemallProduct.getSpecifications());
			orderGoods.setAddTime(LocalDateTime.now());
			orderGoodsService.add(orderGoods);

			// 扣减用户账户
			litemallUser.setIntegral(litemallUser.getIntegral() - goodsIntegeal);
			litemallUser.setBalance(litemallUser.getBalance().subtract(goodsPrice));
			userService.update(litemallUser);
			order.setOrderStatus(OrderUtil.STATUS_PAY);

			//添加钱包的记录
			LitemallWalletRecord walletRecord = new LitemallWalletRecord();
			walletRecord.setUserId(litemallUser.getId());
			walletRecord.setType(new Byte("2"));
			walletRecord.setModifyAmount(goodsPrice.multiply(new BigDecimal(-1)));
			walletRecord.setModifyIntegral(goodsIntegeal * (-1));
			walletRecord.setPayId(order.getOrderSn());
			walletRecord.setPayTime(LocalDateTime.now());
			walletRecord.setModifyTime(LocalDateTime.now());
			walletRecord.setModifyReason("拼团消费");
			walletRecord.setPayType(new Byte("3"));
			walletRecord.setRecordSn(createSn.createSn());
			walletRecordService.add(walletRecord);

			order.setPayId(walletRecord.getRecordSn());
			order.setPayTime(walletRecord.getPayTime());
			orderService.update(order);

			//向团购表添加记录
			LitemallGroupBuyUser groupBuyUser = new LitemallGroupBuyUser();
			groupBuyUser.setUserId(litemallUser.getId());
			groupBuyUser.setGoodId(litemallGoods.getId());
			groupBuyUser.setGoodName(litemallGoods.getName());
			groupBuyUser.setGroupDetailId(groupId);
			groupBuyUser.setOrderId(order.getId());
			groupBuyUser.setOrderStatus((short)1);
			groupBuyUser.setOrderNum(num);
			groupBuyUser.setUpdateTime(LocalDateTime.now());
			groupBuyUserMapper.insert(groupBuyUser);

		}
		catch (NumberFormatException e) {
			e.printStackTrace();
			txManager.rollback(status);
		}
		txManager.commit(status);
		Map<String, Object> data = new HashMap<>(3);
		data.put("orderStatus", order.getOrderStatus());
		data.put("orderId", order.getId());
		return ResponseUtil.ok(data);

	}

}
